package csgbd.Hotel.GUI;

import csgbd.Hotel.Common.DAO.Default.GuestDAO;
import csgbd.Hotel.Common.DB.ConnectionFactory;
import csgbd.Hotel.Common.Entity.Guest;
import csgbd.Hotel.Common.Facade.Default.HotelFacade;
import csgbd.Hotel.Common.Facade.IHotelFacade;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.MaskFormatter;

/**
 *
 * @author italopessoa
 */
public class jfrmGuest extends javax.swing.JFrame {

    private ArrayList<Guest> guests;
    private GuestDAO guestDAO;
    private MaskFormatter ftmTelefone;
    private IHotelFacade facade;

    /**
     * Creates new form jfrmGuest
     */
    public jfrmGuest() {
        initComponents();
        ConnectionFactory.OpenConnection();
        this.guestDAO = new GuestDAO();
        this.facade = new HotelFacade();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtbGuests = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jtxtId = new javax.swing.JTextField();
        jtxtName = new javax.swing.JTextField();
        jtxtEmail = new javax.swing.JTextField();
        jftxtPhone = new javax.swing.JFormattedTextField();
        jtxtAge = new javax.swing.JTextField();
        jbtnNewGuest = new javax.swing.JButton();
        jbtnEditGuest = new javax.swing.JButton();
        jbtnRemoveGuest = new javax.swing.JButton();
        jbtnClear = new javax.swing.JButton();
        jbtnSearch = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jtbGuests.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null},
                {null, null, null, null, null}
            },
            new String [] {
                "ID", "Name", "Email", "Phone", "Idade"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jtbGuests.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtbGuestsMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtbGuests);

        jLabel1.setText("ID:");

        jLabel2.setText("Name:");

        jLabel3.setText("Email:");

        jLabel4.setText("Phone:");

        jLabel5.setText("Age:");

        jtxtId.setEditable(false);
        jtxtId.setText("jTextField1");
        jtxtId.setEnabled(false);

        jbtnNewGuest.setText("Save");
        jbtnNewGuest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnNewGuestActionPerformed(evt);
            }
        });

        jbtnEditGuest.setText("Update");
        jbtnEditGuest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnEditGuestActionPerformed(evt);
            }
        });

        jbtnRemoveGuest.setText("Remove");
        jbtnRemoveGuest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnRemoveGuestActionPerformed(evt);
            }
        });

        jbtnClear.setText("Clear");
        jbtnClear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnClearActionPerformed(evt);
            }
        });

        jbtnSearch.setText("Search");
        jbtnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnSearchActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jtxtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(259, 259, 259))
                                .addGroup(layout.createSequentialGroup()
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel2)
                                        .addComponent(jLabel1))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jtxtId, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGroup(layout.createSequentialGroup()
                                            .addComponent(jtxtName, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGap(38, 38, 38)
                                            .addComponent(jLabel5)
                                            .addGap(18, 18, 18)
                                            .addComponent(jtxtAge, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(layout.createSequentialGroup()
                                            .addGap(297, 297, 297)
                                            .addComponent(jLabel4)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                            .addComponent(jftxtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jbtnNewGuest)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtnEditGuest)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtnRemoveGuest)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtnClear)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtnSearch)))
                        .addGap(0, 137, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jtxtId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel5)
                    .addComponent(jtxtName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtAge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(15, 15, 15)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jtxtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jftxtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtnNewGuest)
                    .addComponent(jbtnEditGuest)
                    .addComponent(jbtnRemoveGuest)
                    .addComponent(jbtnClear)
                    .addComponent(jbtnSearch))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(25, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnNewGuestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnNewGuestActionPerformed
        Guest guest = new Guest(this.jtxtName.getText(), Integer.parseInt(this.jtxtAge.getText()),
                this.jtxtEmail.getText(), this.jftxtPhone.getText());

        this.newGuest(guest);
//        this.showGuests(false);
    }//GEN-LAST:event_jbtnNewGuestActionPerformed

    private void jtbGuestsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbGuestsMouseClicked
        int linha = this.jtbGuests.getSelectedRow();
        if(linha >-1){
            this.jtxtId.setText(String.valueOf(this.jtbGuests.getValueAt(linha,0)));
            this.jtxtName.setText(String.valueOf(this.jtbGuests.getValueAt(linha,1)));
            this.jtxtEmail.setText(String.valueOf(this.jtbGuests.getValueAt(linha,2)));
            this.jftxtPhone.setText(String.valueOf(this.jtbGuests.getValueAt(linha,3)));
            this.jtxtAge.setText(String.valueOf(this.jtbGuests.getValueAt(linha,4)));
        }
    }//GEN-LAST:event_jtbGuestsMouseClicked

    private void jbtnRemoveGuestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnRemoveGuestActionPerformed
        Guest guest = new Guest(Integer.parseInt(this.jtxtId.getText()));
        this.removeGuest(guest);
    }//GEN-LAST:event_jbtnRemoveGuestActionPerformed

    private void jbtnEditGuestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEditGuestActionPerformed
        Guest guest = new Guest(Integer.parseInt(this.jtxtId.getText()));
        guest.setAge(Integer.parseInt(this.jtxtAge.getText()));
        guest.setEmail(this.jtxtEmail.getText());
        guest.setName(this.jtxtName.getText());
        guest.setPhone(this.jftxtPhone.getText());
        
        this.updateGuest(guest);
    }//GEN-LAST:event_jbtnEditGuestActionPerformed

    private void jbtnClearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnClearActionPerformed
        this.clearGuestValues();
    }//GEN-LAST:event_jbtnClearActionPerformed

    private void jbtnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSearchActionPerformed
        try {
            this.guests = this.facade.SelectGuestByName(this.jtxtName.getText());
        this.showGuests();
        } catch (SQLException ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jbtnSearchActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(jfrmGuest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(jfrmGuest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(jfrmGuest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(jfrmGuest.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new jfrmGuest().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtnClear;
    private javax.swing.JButton jbtnEditGuest;
    private javax.swing.JButton jbtnNewGuest;
    private javax.swing.JButton jbtnRemoveGuest;
    private javax.swing.JButton jbtnSearch;
    private javax.swing.JFormattedTextField jftxtPhone;
    private javax.swing.JTable jtbGuests;
    private javax.swing.JTextField jtxtAge;
    private javax.swing.JTextField jtxtEmail;
    private javax.swing.JTextField jtxtId;
    private javax.swing.JTextField jtxtName;
    // End of variables declaration//GEN-END:variables

    private void getGuests(){
        try {
            this.guests = this.facade.SelectAllGuests();
        } catch (SQLException ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void showGuests() {
        //this.getGuests();
        DefaultTableModel model = (DefaultTableModel) this.jtbGuests.getModel();
        model.setNumRows(0);

        for (Guest guest : this.guests) {
            model.addRow(new Object[]{guest.getId(), guest.getName(), guest.getEmail(), guest.getPhone(), guest.getAge()});
        }
    }
    
    private void newGuest(Guest guest){
        try {
            this.facade.NewGuest(guest);
        } catch (SQLException ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(null, "Guest saved sucefull!");
    }
    
    private void removeGuest(Guest guest){
        try {
            this.facade.RemoveGuest(guest);
        } catch (SQLException ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(null, "Guest removed sucefull!");
//        this.showGuests(false);
        this.clearGuestValues();
    }
    
    private void updateGuest(Guest guest){
        try {
            this.guestDAO.Update(guest);
        } catch (SQLException ex) {
            Logger.getLogger(jfrmGuest.class.getName()).log(Level.SEVERE, null, ex);
        }
        JOptionPane.showMessageDialog(null, "Guest updated sucefull!");
//        this.showGuests(false);
        this.clearGuestValues();
    }
    
    private void clearGuestValues(){
        this.jtxtId.setText("");
        this.jtxtName.setText("");
        this.jtxtEmail.setText("");
        this.jftxtPhone.setText("");
        this.jtxtAge.setText("");
    }
    
    @Override
    public void setVisible(boolean isVisible){
        if(isVisible){
            super.setVisible(isVisible);
//            this.showGuests(false);
        }else{
            super.setVisible(isVisible);
        }
    }
}
